package com.etop.jansing.dao;

import com.etop.jansing.entities.Resource;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jansing on 2015/10/25.
 */
@Repository("resourceDao")
public class ResourceDao extends BaseDao<Resource> {

    public List<Resource> list() {
        return getSession().createQuery("from Resource r where r.valid=true").list();
    }

    public Resource getRootResource() {
        Resource rootResource = (Resource) getSession()
                .createQuery("from Resource r where r.valid=true and r.parent is null")
                .uniqueResult();
        return rootResource;
    }

    //todo 使用with子句试试
    public List<Resource> getLeafResourceList(){
        return getSession().createQuery("select r from Resource r left join r.subList sub" +
                " where r.valid=true and sub is null")
                .list();
    }

    public Resource getByNameIgnoreValid(String name) {
        return (Resource) getSession().createQuery("from Resource r where r.name=:name")
                .setString("name", name)
                .uniqueResult();
    }

    /**
     * 资源的使用情况
     *
     * @param resource
     * @return
     */
    public int isUsing(Resource resource) {
        Session session = getSession();
        return session.createQuery("from Role r left join  r.resourcePermissionList rp" +
                " left join rp.resource re " +
                " where r.valid=true and re.id=:id")
                .setLong("id", resource.getId())
                .list()
                .size();
    }
}
